package com.sr.wslr.front.cfg;

import com.sr.wslr.common.util.AnnotationScanner;
import com.sr.wslr.service.elasticsearch.ESUtils;
import com.sr.wslr.service.elasticsearch.annotation.ESEntity;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Iterator;
import java.util.Set;


@ConfigurationProperties(prefix = "es", ignoreUnknownFields = false)
@Configuration
@Slf4j
public class EsClientConfig {
	
	@Getter
	@Setter
	private Cfg cfg;
	
	@Getter
	@Setter
	public static class Cfg {
		String scanPacakge;
		String clusterName;
		int port;
		String ip;
		String indexName;
	}
	
	@Bean(name = "esClient")
	public Client getESClient(){
		Client client = null;
		try {
			client = TransportClient.builder().build().addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(cfg.getIp()), cfg.getPort()));
			// 创建索引以及mapping
			initESIndex(client);
		} catch (UnknownHostException e) {
			log.error(e.getMessage());
		} catch (Exception e){
			log.error(e.getMessage());
		}
        return client;
	}
	
	public void initESIndex(Client client) throws Exception{
		AnnotationScanner scanner = new AnnotationScanner(new String[]{cfg.getScanPacakge()}, ESEntity.class);
		Set<Class<?>> set = scanner.getClassSet();
		Iterator<Class<?>> it = set.iterator();
		while(it.hasNext()){
			ESUtils.initIndexAndMapping(client, cfg.getIndexName(), it.next());
		}
		
	}
	
}
